package com.gxuwz.com_property.interceptor;

import com.gxuwz.com_property.utils.JwtUtil;
import com.gxuwz.com_property.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*") // 拦截所有请求
public class JwtRequestFilter implements Filter {
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        System.out.println("执行了过滤器的内容");

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        // 将登录请求排除在外
        String requestURI = httpRequest.getRequestURI();
        if (requestURI.equals("/api/login") || requestURI.contains("/swagger-ui.html") || requestURI.equals("/captcha.jpg") || requestURI.equals("/mail")
                || requestURI.equals("/face/vef")) {
            chain.doFilter(request, response);
            return;
        }


        // 从请求头中获取 Authorization 字段
        final String authorizationHeader = httpRequest.getHeader(HttpHeaders.AUTHORIZATION);

        boolean isAuthenticated = false;

        // 如果存在 Authorization 头，并且以 "Bearer " 开头（表示传递了 JWT 令牌）
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7);

            // 打印令牌内容
            System.out.println("JwtRequestFilter:Token: " + token);

            if (jwtUtil.validateToken(token)) {

                // 从令牌中提取用户名
                String username = jwtUtil.extractUsername(token);
                System.out.println("username"+username);

                // 检查 Redis 中是否存在该令牌
                boolean tokenExistsInRedis = redisUtil.hasKey(token);

                // 如果 Redis 中存在令牌，认证通过
                if (tokenExistsInRedis) {
                    isAuthenticated = true;
                }
            }
        }

        /**
         * Authorization为空，执行该方法
         * */
        // 如果未经授权，则返回 HTTP 401 Unauthorized 错误

        if (!isAuthenticated) {
            System.out.println("Authorization为空");
            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }

        chain.doFilter(request, response);
    }



    @Override
    public void init(FilterConfig filterConfig) {}

    @Override
    public void destroy() {}
}
